import php.Lib;
import php.db.Manager;

class RSSParser {

	public var url: String;
	private var channel: Xml;
	
	public function new(url: String) 
	{
		this.url=url;
		try 
		{
			var str = php.io.File.getContent(url); 
			channel = Xml.parse(str).firstElement().firstElement();
		}catch(e:Dynamic) {trace(e); return;}
	}
		
	public function getChannelTitle():String
	{
		for(node in channel.elementsNamed("title") )
		{
			return node.firstChild().toString();
		}
		throw new String("invalid rss: channel has no title");
	}
		
	public function getChannelLink():String
	{
		for(node in channel.elementsNamed("link") )
		{
			return node.firstChild().toString();
		}
		throw new String("invalid rss: channel has no link");
	}
	
	public function getImageUrl():String
	{
		for(node in channel.elementsNamed("image") )
		{
			return node.firstElement().firstChild().toString();
		}
		throw new String("channel has no image");
	}
	
	private function myNodeValue(node:Xml):String
	{
		var str:String = "";
		if (node.firstChild() != null) 
			for (x in node) { str += x.nodeValue; }
		return str;
	}
	
	public function getItems():Array<Item>
	{
		var items = new Array<Item>();
		var ititle:String = "", ilink:String = "", idescription:String = "", idate:String = "", author:String="", category:String="";
		for(item in channel.elementsNamed("item") ) 
		{ 
			ititle = ""; ilink = ""; idescription = ""; idate = ""; author = ""; category = "";
			for (node in item.elementsNamed("title") ) { ititle = myNodeValue(node); }
			for (node in item.elementsNamed("link") ) {	ilink = myNodeValue(node); }
			for (node in item.elementsNamed("description") ) { idescription = myNodeValue(node); }
			for (node in item.elementsNamed("pubDate") ) {	idate = myNodeValue(node); }
			for (node in item.elementsNamed("author") )	{ author = myNodeValue(node); }
			for (node in item.elementsNamed("category") ) {	category = myNodeValue(node); }
			
			var newItem:Item;
			if (ititle != "" && ilink != "" && idescription != "" && idate != "")
			{
				newItem= new Item(ititle, ilink, idescription, idate);
				if (author != "") newItem.setAuthor(author); 
				if (category != "") newItem.setCategory(category);
				items.push(newItem);
			}
			else { throw new String ("something wrong"); }
		}
		return items;
	}  
}